import {
	resPost
} from "../common/http.request";

export const pagingMixin = {
	data() {
		return {
			dataList: [],
			dataListParams: {
				page: 1,
				init: false,
				loadMore: true,
				loading: false,
				len: 0
			}
		}
	},
	methods: {

		_init_data(apiName, params = {}, opts = {}) {
			this.$nextTick(() => {
				opts = {
					showLoading: true,
					callBack: null,
					lastCallBack: null,
					listName: 'dataList',
					reset: true,
					msg: '',
					params: {
						page: 1,
						loadMore: true,
						init: false,
						loading: false,
						len: 0,
					},
					...opts
				}

				let pageParamsName = opts.listName + 'Params'

				this[pageParamsName] = {
					page: 1,
					loadMore: true,
					init: false,
					loading: false,
					len: 0,
					...opts.params,
					params,
					apiName
				}
				this._load_data(opts)
			})
		},
		_load_data(opts = {}) {

			this.$nextTick(() => {
				opts = {
					showLoading: false,
					callBack: null,
					lastCallBack: null,
					listName: 'dataList',
					reset: false,
					msg: '',
					option: {},
					...opts
				}
				let pageParamsName = opts.listName + 'Params'
				let pageParams = this[pageParamsName]
				if (pageParams.loading) return
				if (!pageParams.loadMore) return
				if (!pageParams.apiName) return
				this[pageParamsName].loading = true
				let list = this[opts.listName]
				if (opts.showLoading) this.$loading()
				resPost(pageParams.apiName, {
					page: pageParams.page,
					...pageParams.params
				}, {}, opts.option).then(({
					data,
					pageCount
				}) => {
					if (opts.callBack && typeof opts.callBack === 'function') {
						data = opts.callBack(data, pageParams.page, pageCount)
					}
					if (opts.reset) {
						list = data
					} else {
						list = list.concat(data)
					}

					if (pageCount > pageParams.page) {
						pageParams.page++
					} else {
						pageParams.loadMore = false
					}
					this.$nextTick(() => {
						pageParams.loading = false
						pageParams.init = true
						pageParams.len = list.length
						this[pageParamsName] = pageParams
						this[opts.listName] = list
					})
					if (opts.lastCallBack && typeof opts.lastCallBack === 'function') {
						opts.lastCallBack(this)
					}
					if (opts.showLoading) this.$hide()
					if (opts.msg) this.$toast(opts.msg)
				}).catch(() => {
					pageParams.loading = false
					pageParams.init = true
					pageParams.loadMore = false
					if (opts.reset) list = []
					this[pageParamsName] = pageParams
					this[opts.listName] = list
					if (opts.showLoading) this.$hide()
					if (opts.msg) this.$toast(opts.msg)
				})
			})
		}
	}
}
